package top.ghovos.edgar.springbootproject03.services;

import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVRecord;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.core.io.Resource;
import org.springframework.http.RequestEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import top.ghovos.edgar.springbootproject03.models.RegionStats;

import java.io.*;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;

@Service
public class CoronaVirusDataServices implements InitializingBean {

    private static final String CORONA_VIRUS_DATA_URL = "https://gitee.com/voghost/COVID-19/raw/master/csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_confirmed_global.csv";
    private final List<RegionStats> allRegionStats= new ArrayList<>();

    public List<RegionStats> getAllRegionStats() {
        return allRegionStats;
    }

    @Scheduled(cron = "0 0 1 * * *")
    public void fetchCoronaVirusData() throws IOException {
        //爬取数据
        RequestEntity<Void> requestEntity = (RequestEntity<Void>) RequestEntity
                .get(URI.create(CORONA_VIRUS_DATA_URL))
                .headers(httpHeaders -> httpHeaders.add("User-Agent","Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.198 Safari/537.36"))
                .build();
        ResponseEntity<Resource> exchange = new RestTemplate().exchange(requestEntity,Resource.class);
        Resource body = exchange.getBody();
/**
 * 下文件测试是否爬取成功
 */
//        String pathTemp="/home/voghost/workspaces/test";
//        File fileTemp=new File(pathTemp);
//        if(!fileTemp.exists()){
//            fileTemp.mkdir();
//        }
//        //新建一个文件
//        File newFile = new File(pathTemp+"/"+"CoronaVirus.csv");
//        InputStream inputStream = body.getInputStream();
//        OutputStream outputStream=new FileOutputStream(newFile);
//        int len = 0;
//        byte[] buf = new byte[1024];
//        while ((len = inputStream.read(buf, 0, 1024)) != -1) {
//            outputStream.write(buf, 0, len);
//        }
//        //写入文件
//        outputStream.flush();
//        //关闭流
//        inputStream.close();
//        outputStream.close();


        final String[] FILE_HEADER = {"Province/State","Country","lat","long"};
        CSVFormat format = CSVFormat.DEFAULT.withHeader(FILE_HEADER).withSkipHeaderRecord();
        Reader in =new InputStreamReader(body.getInputStream());
//        Reader in =new FileReader(pathTemp+"/"+"CoronaVirus.csv");

        Iterable<CSVRecord> records=format.parse(in);
        for (CSVRecord record: records){
            RegionStats regionStats=new RegionStats();

            regionStats.setState(record.get(0));
            regionStats.setCountry(record.get(1));
            regionStats.setLatestTotalCases(Integer.parseInt(record.get(record.size()-1)));
            regionStats.setDiffFromPrevDay(Integer.parseInt(record.get(record.size()-1))-Integer.parseInt(record.get(record.size()-2)));

            int lastTenDayCases[]=new int[10];
            for(int i=0;i<10;i++){
                lastTenDayCases[10-i-1]= Integer.parseInt(record.get(record.size()-i-1));
            }
            regionStats.setLastTenDaysCases(lastTenDayCases);

            allRegionStats.add(regionStats);
        }
    }


    @Override
    public void afterPropertiesSet() throws Exception {
        fetchCoronaVirusData();

    }
}
